package com.ruoyi.blog.service.impl;

import java.util.List;

import com.ruoyi.blog.domain.Meta;
import com.ruoyi.blog.service.IBlogAccessService;
import com.ruoyi.blog.service.IBlogCommentService;
import com.ruoyi.blog.service.IBlogLikeService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.blog.mapper.BlogArticleMapper;
import com.ruoyi.blog.domain.BlogArticle;
import com.ruoyi.blog.service.IBlogArticleService;

/**
 * 文章Service业务层处理
 *
 * @author tina
 * @date 2021-06-27
 */
@Service
public class BlogArticleServiceImpl implements IBlogArticleService {
    @Autowired
    private BlogArticleMapper blogArticleMapper;

    @Autowired
    private IBlogAccessService accessService;

    @Autowired
    private IBlogLikeService likeService;

    @Autowired
    private IBlogCommentService commentService;

    /**
     * 查询文章
     *
     * @param id 文章ID
     * @return 文章
     */
    @Override
    public BlogArticle selectBlogArticleById(Long id) {
        return blogArticleMapper.selectBlogArticleById(id);
    }

    private List<BlogArticle> getArticleList(List<BlogArticle> list) {
        for (BlogArticle article : list) {
            Meta meta = new Meta();
            meta.setViews(accessService.countAccessById(article.getId()));
            meta.setLikes(likeService.countLikeById(article.getId()));
            meta.setComments(commentService.countCommentById(article.getId()));
            article.setMeta(meta);
        }
        return list;
    }

    /**
     * 查询文章列表
     *
     * @param blogArticle 文章
     * @return 文章
     */
    @Override
    public List<BlogArticle> selectBlogArticleList(BlogArticle blogArticle) {
        return getArticleList(blogArticleMapper.selectBlogArticleList(blogArticle));
    }

    /**
     * 新增文章
     *
     * @param blogArticle 文章
     * @return 结果
     */
    @Override
    public int insertBlogArticle(BlogArticle blogArticle) {
        blogArticle.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        blogArticle.setCreateTime(DateUtils.getNowDate());
        return blogArticleMapper.insertBlogArticle(blogArticle);
    }

    /**
     * 修改文章
     *
     * @param blogArticle 文章
     * @return 结果
     */
    @Override
    public int updateBlogArticle(BlogArticle blogArticle) {
        blogArticle.setUpdateTime(DateUtils.getNowDate());
        return blogArticleMapper.updateBlogArticle(blogArticle);
    }

    /**
     * 批量删除文章
     *
     * @param ids 需要删除的文章ID
     * @return 结果
     */
    @Override
    public int deleteBlogArticleByIds(Long[] ids) {
        return blogArticleMapper.deleteBlogArticleByIds(ids);
    }

    /**
     * 删除文章信息
     *
     * @param id 文章ID
     * @return 结果
     */
    @Override
    public int deleteBlogArticleById(Long id) {
        return blogArticleMapper.deleteBlogArticleById(id);
    }
}
